package com.gljr.exam;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;

import com.gljr.exam.dao.ExamPaperQuestionRepository;
import com.gljr.exam.dao.InviteCodeRepository;
import com.gljr.exam.dao.UserRepository;
import com.gljr.exam.domain.InviteCode;
import com.gljr.exam.domain.User;
import com.gljr.exam.tools.ExamUniTools;

@SpringBootApplication
public class ExamApplication extends SpringBootServletInitializer {

	@Bean
	InitializingBean seedDatabase(final UserRepository repository) {
		return new InitializingBean() {

			@Override
			public void afterPropertiesSet() throws Exception {
				// repository.save(new User("admin", "admin", "管理员", true,
				// true));
			}
		};
	}

	@Bean
	InitializingBean insertInviteCode(final InviteCodeRepository repository) {
		return new InitializingBean() {
			@Override
			public void afterPropertiesSet() throws Exception {
				for (int i = 0; i < 1; i++) { // 生成邀请码
					String string = ExamUniTools.generateSixRandom();

					if (repository.findInviteCodeByInviteCode(string) == null) {
						repository.save(new InviteCode(string, true));
					} else {
						break;
					}
				}
			}
		};
	}

	@Bean
	InitializingBean insertExamPaper(final ExamPaperQuestionRepository repository) {
		return new InitializingBean() {

			@Override
			public void afterPropertiesSet() throws Exception {
				// repository.save(new ExamPaperQuestion(1L, "问题1", "选项A",
				// "选项B", "选项A"));

			}
		};
	}

	@Bean
	CommandLineRunner exampleQuery(final UserRepository repository) {
		return new CommandLineRunner() {

			@Override
			public void run(String... args) throws Exception {
				User user = repository.findByUsernameIgnoreCase("Bbb");
				System.out.println(user);
			}
		};
	}

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(ExamApplication.class);
	}

	public static void main(String[] args) {
		SpringApplication.run(ExamApplication.class, args);
	}

}
